//
//  OperationBillManagerMainVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/11/9.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "OperationBillManagerMainVC.h"
#import "OperationBillManagerListVC.h"
#import "CaoZuoDanQueryNavBar.h"
#import "OperationBillMainModel.h"
#import "OperationBillListCell.h"
#import "OperationBillListHeadView.h"
#import "OperationBillDetailVC.h"
#import "ErWeiMaView.h"

@interface OperationBillManagerMainVC ()<ZJScrollPageViewDelegate,UITableViewDelegate,UITableViewDataSource>{
    int page;
    int type;
}

@property (nonatomic, strong) CaoZuoDanQueryNavBar *navBar;
@property (nonatomic, strong) ZJSegmentStyle *menuStyle;//菜单栏
@property (nonatomic, strong) NSArray<NSString *> *titles;
@property (nonatomic, strong) ZJScrollPageView *scrollPageView;
@property (nonatomic, strong) UIView *scrollPageBGView;
@property (nonatomic, strong) OperationBillListHeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <OperationBillMainModel *>*array;

@end

@implementation OperationBillManagerMainVC

-(CaoZuoDanQueryNavBar *)navBar {
    if (!_navBar) {
        _navBar = [[CaoZuoDanQueryNavBar alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight)];
        _navBar.titleStr = @"操作单管理";
        __weak_self;
        _navBar.backBlock = ^{
            [weakself.rt_navigationController popViewControllerAnimated:YES];
        };
        _navBar.changeBlock = ^(NSInteger status) {
            [weakself changeView:status];
        };
    }
    return _navBar;
}

- (void)changeView:(NSInteger)status {
    if (status == 1) {
        self.scrollPageBGView.hidden = NO;
        self.scrollPageView.hidden = NO;
        self.tableView.hidden = YES;
        self.headView.hidden = YES;
    }else {
        self.scrollPageBGView.hidden = YES;
        self.scrollPageView.hidden = YES;
        self.tableView.hidden = NO;
        self.headView.hidden = NO;
    }
}

-(OperationBillListHeadView *)headView {
    if (!_headView) {
        _headView = [[OperationBillListHeadView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, 40)];
        _headView.hidden = YES;
        __weak_self;
        _headView.clickBlock = ^(int type) {
            __strong_self;
            strongSelf->page = 1;
            strongSelf->type = type;
            [strongSelf requestForList];
        };
    }
    return _headView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headView.nim_bottom, ScreenW, ScreenH - BottomHeight - NaviHeight - self.headView.nim_height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.hidden = YES;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

-(NSMutableArray<OperationBillMainModel *> *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}


-(ZJScrollPageView *)scrollPageView {
    if (!_scrollPageView) {
        _scrollPageView = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, ScreenH - BottomHeight - NaviHeight) segmentStyle:self.menuStyle titles:self.titles parentViewController:self delegate:self];
    }
    return _scrollPageView;
}

-(UIView *)scrollPageBGView {
    if (!_scrollPageBGView) {
        _scrollPageBGView = [[UIView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, 40)];
        _scrollPageBGView.backgroundColor = [UIColor whiteColor];
    }
    return _scrollPageBGView;
}

-(ZJSegmentStyle *)menuStyle {
    if (!_menuStyle) {
        _menuStyle = [ZJSegmentStyle new];
        _menuStyle.autoAdjustTitlesWidth = YES;
        _menuStyle.showLine = YES;//显示下划线
        _menuStyle.scrollTitle = YES;//设置标题栏可以滚动
        _menuStyle.segmentViewBounces = YES;//设置滚动标题栏有弹性
        _menuStyle.scaleTitle = YES;//设置选中标题缩放
        _menuStyle.scrollContentView = YES;//内容可以滑动
        _menuStyle.normalTitleColor = HexColor(0x9C9DB3);
        _menuStyle.selectedTitleColor = Color_ThemeColor;
        _menuStyle.scrollLineColor = Color_ThemeColor;
        _menuStyle.scrollLineWidth = 12;
        _menuStyle.segmentHeight = 40;
        _menuStyle.titleBigScale = 1.1;
        _menuStyle.titleFont = [UIFont systemFontOfSize:14];
    }
    return _menuStyle;
}

-(NSArray<NSString *> *)titles {
    if (!_titles) {
        _titles = @[@"全部",@"受理",@"驳回",@"收货",@"调度",@"出发"];
    }
    return _titles;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.scrollPageBGView];
    [self.view addSubview:self.scrollPageView];
    page = 1;
    type = 0;
    [self.view addSubview:self.headView];
    [self.view addSubview:self.tableView];
    [self requestForList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self judgeNeedUpdate];
}

//判断是否需要更新
-(void)judgeNeedUpdate {
    //https://apps.apple.com/us/app/云物流商/id1540907919
    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1540907919"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    NSOperationQueue *queue = [NSOperationQueue new];
    __weak_self;
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
            }else{
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        NSString *appstoreVersion = [receiveStatusDic valueForKey:@"version"];
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
        if ([appstoreVersion compare:currentVersion options:NSNumericSearch] == NSOrderedDescending) {
            //需要更新
            NSLog(@"需要更新");
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"已检测到新版本，请前往更新" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSString *urlStr = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?mt=8",@"1540907919"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:sureAction];
                [alert addAction:cancleAction];
                [weakself presentViewController:alert animated:YES completion:nil];
            });
        }else {
            //不需要更新
            NSLog(@"不需要更新");
        }
    }];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(type) forKey:@"type"];
    [dic setObject:@(page) forKey:@"page"];
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillFinishList params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.array removeAllObjects];
                self.array = [OperationBillMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.array enumerateObjectsUsingBlock:^(OperationBillMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.billStatus = YES;
                }];
            }else {
                NSArray *array = [OperationBillMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    ((OperationBillMainModel *)obj).billStatus = YES;
                }];
                [self.array addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    OperationBillManagerListVC<ZJScrollPageViewChildVcDelegate> * childVC = (OperationBillManagerListVC *)reuseViewController;
    OperationBillManagerListVC *vc = [OperationBillManagerListVC new];
    if (index == 0) {
        //@"全部"
        vc.status = 0;
    }else if (index == 1) {
        //@"受理"
        vc.status = 1;
    }else if (index == 2) {
        //@"驳回"
        vc.status = 2;
    }else if (index == 3) {
        //@"收货"
        vc.status = 3;
    }else if (index == 4) {
        //@"调度"
        vc.status = 4;
    }else if (index == 5) {
        //@"途中"
        vc.status = 5;
    }
    childVC = vc;
    return childVC;
}

//子控制器实现完整生命周期
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OperationBillListCell *cell = [OperationBillListCell OperationBillListCellWithTableView:tableView];
    OperationBillMainModel *model = self.array[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.detailBlock = ^{
        //详情
        OperationBillDetailVC *vc = [OperationBillDetailVC new];
        vc.os_id = model.os_id;
        vc.billStatus = YES;
        vc.hidesBottomBarWhenPushed = YES;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.codeBlock = ^{
        //查看二维码
        ErWeiMaView *alert = [ErWeiMaView new];
        alert.o_id = model.o_id;
        [alert showInView:MAIN_WINDOW];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    OperationBillListCell *cell = [OperationBillListCell OperationBillListCellWithTableView:tableView];
    cell.model = self.array[indexPath.row];
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OperationBillMainModel *model = self.array[indexPath.row];
    OperationBillDetailVC *vc = [OperationBillDetailVC new];
    vc.os_id = model.os_id;
    vc.billStatus = YES;
    vc.hidesBottomBarWhenPushed = YES;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

@end
